package org.zju.demo.service.impl;

import org.zju.demo.model.User;
import org.zju.demo.service.intf.UserIntf;
import org.zju.demo.utils.Constant;
import org.zju.demo.utils.HibernateUtil;

import java.util.List;

/**
 * Created by admin on 2015/8/26.
 */
public class UserImpl implements UserIntf {

    public User findByUsername(String username) {
        String hql = "from User where username=?";
        String parameter[] = {username};
        return (User) HibernateUtil.objectQuery(hql, parameter);
    }

    public int register(String username, String nickname, String password) {
        User user = findByUsername(username);
        if (user != null) {
            return Constant.ALREADY_EXISTS;
        }

        user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPassword(password);
        user.setLevel(0);

        return HibernateUtil.saveIfNotExists(user);
    }

    public int login(String username, String password) {
        User user = findByUsername(username);
        if (user == null) {
            return Constant.NO_SUCH_USER;
        }
        if (user.getPassword().equals(password)) {
            return Constant.SUCCESS;
        }
        return Constant.MISMATCH;
    }

    public boolean update(User user) {
        User oldUser = findByUserId(user.getUserId());
        if (oldUser == null) {
            return false;
        }
        HibernateUtil.update(user);
        return true;
    }

    public boolean saveOrUpdate(User user) {
        HibernateUtil.saveOrUpdate(user);
        return true;
    }

    public List<User> getAllUser() {
        String hql = "from User";
        List<User> userList = HibernateUtil.executeQuery(hql, null);
        return userList;
    }

    public User findByUserId(int userId) {
        String hql = "from User where userId=?";
        String[] paramters = {Integer.toString(userId)};
        return (User)HibernateUtil.objectQuery(hql, paramters);
    }
}
